package cloud.smalla.interceptor;

import cloud.smalla.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述
 * 全局日志打印
 *
 * @author 邱彦祥
 * 时间：2023-03-31 22:40
 */
@Component
@Slf4j
public class LogInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        log.info("=====================request start=========================");
        String jwt = request.getHeader(JwtUtils.getHeader());
        //如果请求头中有token
        if (StringUtils.isNotBlank(jwt)) {
            Claims claim = JwtUtils.getClaimsByToken(jwt);
            if (claim != null) {
                String userId = claim.getSubject();
                log.info("request userId:{}", userId);
            }
        }
        log.info("request uri:{}", request.getRequestURL());
        log.info("request method:{}", request.getMethod());
        log.info("=====================request end=========================");
        return true;
    }

}
